import { BadGatewayException, Body, Controller, Get, Post, Query, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { InjectModel } from 'nestjs-typegoose';
import { User } from 'src/decorator/user.decorator';
import { QudaobaoModel } from 'src/mongodb/models/qudaobaoModel/qudaobaoModel';
import { LanxiModel } from 'src/mongodb/models/lianxiModel/LanxiModel';
import { deleteCompanyDto, getCompanyDto } from '../companyApi/companyDto/companyDto';
import { qudaoEnum } from 'src/modules/app/operatApi/idfaapi';

@Controller('web')
@UseGuards(AuthGuard("jwtweb"))
export class ChannelController {

    constructor(
        @InjectModel(QudaobaoModel) private readonly channel: ModelType<QudaobaoModel>,
        @InjectModel(LanxiModel) private readonly contact: ModelType<LanxiModel>
    ) { }

    /**
     * @Description: 添加渠道包
     * @param channel {String} 渠道名
     * @param mark {String}  渠道包好
     * @return: Promise
     */
    @Post('addChannel')
    async addChannel(@Body() body, @User() user) {
        try {
            let conten = []
            body.mark.forEach(element => {
                conten.push({
                    mark: element,
                    channel: body.channel,
                    createTime: Math.floor(Date.now() / 1000),
                    updateTime: Math.floor(Date.now() / 1000),
                    userid: user._id,
                    username: user.name
                })
            });
            try {
                await this.channel.create(conten)
                return { code: 200, message: '添加成功' }
            } catch (error) {
                console.log(error.keyValue);
            }
        } catch (error) {
            throw new BadGatewayException(error)
        }

    }



    @Get('qudaoList')
    qudaoList() {
        let qudao: string[] = []
        for (let key in qudaoEnum) {
            qudao.push(key)
        }
        return qudao
    }






    /**
  * @Description: 查询渠道包
  * @param pageNo {Number} 页码
  * @param pageSize {Number}  每页条数
  * @return: Promise
  */
    @Get('getChannel')
    async getChannel(@Query() query: getCompanyDto, @User() user) {
        try {

            let data: { pageNo: number | string, pageSize: number | string } = query
            if (typeof data.pageNo == 'string') {
                data.pageNo = parseInt(data.pageNo)
            }
            if (typeof data.pageSize == 'string') {
                data.pageSize = parseInt(data.pageSize)
            }

            // const docs = await this.channel.aggregate([
            //     { $lookup: { from: "jihuomodels", localField: "mark", foreignField: "ditch", as: "qudaotjmodel" } },
            // ])

            if (user.name == 'admin') {
                const total = await this.channel.countDocuments()
                const userlist = await this.channel.find().skip((data.pageNo - 1) * data.pageSize).limit(data.pageSize).sort({ 'mark': 1 });
                return { total, data: userlist }
            } else {
                const total = await this.channel.countDocuments({ userid: user._id })
                const userlist = await this.channel.find({ userid: user._id }).skip((data.pageNo - 1) * data.pageSize).limit(data.pageSize).sort({ 'mark': 1 });
                return { total, data: userlist }
            }

        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



    /**
       * @Description: 删除渠道包
       * @param id {String} 公司id
       * @return: Promise
       */
    @Post('deleteChannel')
    async deleteChannel(@Body() body: deleteCompanyDto, @User() user) {
        try {
            if (user.name == 'admin') {
                const reqlut = await this.channel.findById(body.id)
                await this.channel.deleteOne({ _id: body.id })
                this.contact.deleteMany({ mark: reqlut.mark }).then()
                return { code: 200, message: '删除成功' }
            } else {
                const reqlut = await this.channel.findOne({ _id: body.id, userid: user._id })
                await this.channel.deleteOne({ _id: body.id, userid: user._id })
                this.contact.deleteMany({ mark: reqlut.mark }).then()
                return { code: 200, message: '删除成功' }
            }

        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



    /**
     * @Description: 删除全部渠道包
     * @return: Promise
     */
    @Post('deleteChannelAll')
    async deleteChannelAll(@User() user) {
        try {
            if (user.name == 'admin') {
                await this.channel.deleteMany({})
                this.contact.deleteMany({}).then()
                return { code: 200, message: '删除成功' }
            } else {
                await this.channel.deleteMany({ userid: user._id })
                this.contact.deleteMany({ userid: user._id }).then()
                return { code: 200, message: '删除成功' }
            }


        } catch (error) {
            throw new BadGatewayException(error)
        }
    }


    /**
    * @Description: 批量删除渠道包
    * @return: Promise
    */
    @Post('deleteChannelxz')
    @UseGuards(AuthGuard("jwtweb"))
    async deleteChannelxz(@Body() body, @User() user) {
        try {
            if (user.name == 'admin') {
                await this.channel.deleteMany({ mark: { $gte: parseInt(body.mark[0]), $lte: parseInt(body.mark[1]) } })
                await this.contact.deleteMany({ mark: { $gte: parseInt(body.mark[0]), $lte: parseInt(body.mark[1]) } })
                return { code: 200, message: '删除成功' }
            } else {
                await this.channel.deleteMany({ mark: { $gte: parseInt(body.mark[0]), $lte: parseInt(body.mark[1]) }, userid: user._id })
                await this.contact.deleteMany({ mark: { $gte: parseInt(body.mark[0]), $lte: parseInt(body.mark[1]) }, userid: user._id })
                return { code: 200, message: '删除成功' }
            }


        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



    /**
    * @Description: 搜索渠道包
    * @return: Promise
    */
    @Get('searchChannel')
    async searchChannel(@Query() query, @User() user) {
        try {

            if (user.name == 'admin') {
                let channellist
                if (query.mark) {
                    channellist = await this.channel.find({ mark: parseInt(query.mark) })
                } else if (query.markqj) {
                    channellist = await this.channel.find({ mark: { $gte: parseInt(query.markqj[0]), $lte: parseInt(query.markqj[1]) } })
                } else {
                    channellist = await this.channel.find({ channel: query.channel })
                }
                return { total: channellist.length, data: channellist }
            } else {
                let channellist
                if (query.mark) {
                    channellist = await this.channel.find({ mark: parseInt(query.mark), userid: user._id })
                } else if (query.markqj) {
                    channellist = await this.channel.find({ mark: { $gte: parseInt(query.markqj[0]), $lte: parseInt(query.markqj[1]) }, userid: user._id })
                } else {
                    channellist = await this.channel.find({ channel: query.channel, userid: user._id })
                }
                return { total: channellist.length, data: channellist }
            }

        } catch (error) {
            throw new BadGatewayException(error)
        }
    }


    /* 修改数据 */
    @Post('updateChannel')
    async updateChannel(@Body() body, @User() user) {
        try {
            if (user.name == 'admin') {
                await this.channel.updateOne({ _id: body.setChannel.id }, { ...body.setChannel, updateTime: Math.floor(Date.now() / 1000) })
                return { code: 200, message: '修改成功' }
            } else {
                await this.channel.updateOne({ _id: body.setChannel.id, userid: user._id }, { ...body.setChannel, updateTime: Math.floor(Date.now() / 1000) })
                return { code: 200, message: '修改成功' }
            }

        } catch (error) {
            throw new BadGatewayException(error)
        }
    }


    /* 区间修改 */
    @Post('updateqjChannel')
    async updateqjChannel(@Body() body, @User() user) {
        try {
            if (user.name == 'admin') {
                await this.channel.updateMany({ mark: { $gte: parseInt(body.qjarr[0]), $lte: parseInt(body.qjarr[1]) } }, { ...body.qjupdata, updateTime: Math.floor(Date.now() / 1000) })
                return { code: 200, message: '修改成功' }
            } else {
                await this.channel.updateMany({ mark: { $gte: parseInt(body.qjarr[0]), $lte: parseInt(body.qjarr[1]) }, userid: user._id }, { ...body.qjupdata, updateTime: Math.floor(Date.now() / 1000) })
                return { code: 200, message: '修改成功' }
            }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }

}
